//
//  HMOAuthViewController.swift
//  WeiBoSwift
//
//  Created by hgj on 2016/11/16.
//  Copyright © 2016年 HuGuoJian. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMOAuthViewController: UIViewController {

    let webView = UIWebView()
//    lazy var webView = UIWebView()
    lazy var progressHUD = HMProgressView()
    
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setNavBar()
        
        // 1.加载请求授权界面
        loadOAuth()
        
        setProgressView()
    }
    
    private func setNavBar() {
        
        title = "授权登录"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭",target: self, action: #selector(clickCloseButton))
        
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", target: self, action: #selector(clickTestAccount))
    }
    
    @objc private func clickCloseButton() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func clickTestAccount() {

        let str = "document.getElementById('userId').value = '18761646212', document.getElementById('passwd').value = '1542517441'"
        webView.stringByEvaluatingJavaScript(from: str)
    }
    
    private func loadOAuth() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = URL(string: urlString)
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
    }
    
    private func setProgressView() {
        self.view.addSubview(progressHUD)
        progressHUD.frame.origin.y = 64
    }
    
    // 页面将要消失的时候dismiss指示器
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
}

// MARK: ----- 协议方法 UIWebView -----
extension HMOAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
        progressHUD.startAnimation()//------
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
        progressHUD.endAinmation()//-----
    }
    
    // 2.拿到code
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlStr = request.url?.absoluteString ?? ""
        let fag = "code="
        
        if urlStr.contains(fag) {
            // 截取.后面拼接的那部分
            let query = request.url?.query ?? ""
            
            // 获取code
            let code = (query as NSString).substring(from: fag.characters.count)
            
            HMUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (isSucess) in
                
                if !isSucess{
                    SVProgressHUD.showError(withStatus: errTip)
                    return
                }
                
                // 成功
                NotificationCenter.default.post(name: NSNotification.Name(kChoseRootViewController), object: "welcom")
            })
            
            // 必须要在这里return 阻止继续加载网页,因为我们已经准备好了成功界面
            return false
        }
        
        return true
    }
}
